const Mock = require('mockjs')
const sha1 = require('js-sha1')
const { find: findOrgUnit } = require('./org-units')
const { add: addUserRole, list: listUserRoles } = require('./user-roles')
Mock.Random.extend({
  phone: function() {
    const phonePrefix = ['132', '135', '189']
    return this.pick(phonePrefix) + Mock.mock(/\d{8}/)
  }
})

const Users = [{
  id: 1,
  orgUnitId: 1,
  phoneNumber: '13111231145',
  password: sha1('12345678'),
  nickname: Mock.Random.cname(),
  registerTime: Mock.Random.datetime(),
  disabled: 0,
  roles: ['Admin']
}]

addUserRole(1, 1, 'Admin')

for (let i = 2; i < 6; ++i) {
  Users.push(Mock.mock({
    id: i,
    orgUnitId: (i % 3) + 1,
    phoneNumber: Mock.Random.phone(),
    password: sha1('12345678'),
    nickname: Mock.Random.cname(),
    registerTime: Mock.Random.datetime(),
    disabled: 0,
    roles: ['Manager', 'ShopManager']
  }))

  addUserRole((i % 3) + 1, i, 'Manager')
  addUserRole((i % 3) + 1, i, 'ShopManager')
}

for (let i = 6; i < 25; ++i) {
  Users.push(Mock.mock({
    id: i,
    orgUnitId: (i % 3) + 1,
    phoneNumber: Mock.Random.phone(),
    password: sha1('12345678'),
    nickname: Mock.Random.cname(),
    registerTime: Mock.Random.datetime(),
    disabled: 0,
    roles: ['DM']
  }))
  addUserRole((i % 3) + 1, i, 'DM')
}

function addUser(phoneNumber, role, orgUnitId) {
  const u = findUser(phoneNumber)
  if (u) {
    addUserRole(orgUnitId, u.id, role)
  } else {
    Users.push({
      id: Users[Users.length - 1].id + 1,
      orgUnitId: orgUnitId,
      phoneNumber: phoneNumber,
      password: sha1('88888888'),
      nickname: '',
      registerTime: new Date(),
      disabled: 0,
      roles: [role]
    })
    addUserRole(orgUnitId, Users[Users.length - 1].id, role)
  }
}

/**
 * 查找用户,如果没有找到返回null
 * @param {String} phoneNumber 手机号
 */
function findUser(phoneNumber) {
  let r = null
  Users.some(u => {
    if (u.phoneNumber === phoneNumber) {
      r = u
      return true
    }
  })
  if (r) {
    r.roles = listUserRoles(r.id).map(item => item.role)
    const o = findOrgUnit(r.orgUnitId)
    if (o) {
      r.orgUnitType = o.type
      r.orgUnitName = o.name
    }
  }
  return r
}

function findUserById(id) {
  let r = null
  id = id ? parseInt(id) : null
  Users.some(u => {
    if (u.id === id) {
      r = u
      return true
    }
  })
  if (r) {
    r.roles = listUserRoles(r.id).map(item => item.role)
  }
  return r
}

function list(page, limit, phoneNumber, orgUnitId, role, nickname, text) {
  limit = Math.max(1, Math.min(parseInt(limit), 50))
  page = Math.max(parseInt(page), 1)
  orgUnitId = orgUnitId ? parseInt(orgUnitId) : null
  let mocks = Users.filter(item => {
    if (orgUnitId && item.orgUnitId !== orgUnitId) return false
    if (role && item.roles && item.roles.indexOf(role) === -1) return false
    if (nickname && (!item.nickname || item.nickname.indexOf(nickname) === -1)) return false
    if (phoneNumber && (!item.phoneNumber || item.phoneNumber.indexOf(phoneNumber) === -1)) return false
    return !(text && ((!item.nickname || item.nickname.indexOf(text) === -1) && (!item.phoneNumber || item.phoneNumber.indexOf(text) === -1)))
  })
  const total = mocks.length
  mocks = mocks.filter((u, index) => index < limit * page && index >= limit * (page - 1))
  mocks = mocks.map(d => {
    const o = findOrgUnit(d.orgUnitId)
    const roles = listUserRoles(d.id).map(item => item.role)
    const theItem = { ...d, orgUnitName: o ? o.name : '', orgUnitType: o ? o.type : null }
    theItem.roles = roles
    return theItem
  }).map(d => JSON.parse(JSON.stringify(d))).map(d => {
    d.password = ''
    return d
  })
  return { success: true, data: { total: total, records: mocks }}
}

module.exports = { Users, findUser, list, findUserById, addUser }
